/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.dubbo.rpc.filter;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;

import com.swak.exception.AopWrapException;
import com.swak.exception.BusinessException;

/**
 * ExceptionInvokerFilter
 * <p>
 * Functions:
 * <ol>
 * <li>unexpected exception will be logged in ERROR level on provider side. Unexpected exception are unchecked
 * exception not declared on the interface</li>
 * <li>Wrap the exception not introduced in API package into RuntimeException. Framework will serialize the outer exception but stringnize its cause in order to avoid of possible serialization problem on client side</li>
 * </ol>
 */
@Activate(group = CommonConstants.PROVIDER)
public class ExceptionFilter implements Filter, Filter.Listener {
	private Logger logger = LoggerFactory.getLogger(ExceptionFilter.class);

	@Override
	public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
		return invoker.invoke(invocation);
	}

	/**
	 * 不做任何处理, 直接抛出所有的异常
	 */
	@Override
	public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
		if (appResponse.hasException()) {

			/*
			 * 获取内部真实的异常
			 */
			Throwable e = appResponse.getException();
			Throwable error = e.getCause() != null ? e.getCause() : e;

			/*
			 * directly throw if it's checked exception
			 */
			if (!(e instanceof RuntimeException) && (e instanceof Exception)) {
				return;
			}
			
			/*
			 * directly throw if it's dubbo exception
			 */
			if (e instanceof RpcException) {
                return;
            }

			/*
			 * 对Aop动态代理中抛出的异常进一步处理
			 */
			if (error instanceof AopWrapException) {
				error = error.getCause() != null ? error.getCause() : error;
			}

			/*
			 * 对应业务异常不需要打印
			 */
			if (!(error instanceof BusinessException)) {
				this.onError(error, invoker, invocation);
			}

			/*
			 * 重新设置异常
			 */
			appResponse.setException(error);
		}
	}

	@Override
	public void onError(Throwable e, Invoker<?> invoker, Invocation invocation) {
		logger.error("Got exception which called by " + RpcContext.getContext().getRemoteHost() + ". service: "
				+ invoker.getInterface().getName() + ", method: " + invocation.getMethodName() + ", exception: "
				+ e.getClass().getName() + ": " + e.getMessage(), e);
	}

	// For test purpose
	public void setLogger(Logger logger) {
		this.logger = logger;
	}
}